import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';
import 'package:m6/Public/manager/app_manager.dart';
import 'package:m6/business/login/login_controller.dart';
import 'package:m6/business/login/pravicy.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final loginCon = Get.put(LoginController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          actions: <Widget>[
            IconButton(
              icon: Image.asset("recource/images/customer_icon.png"),
              tooltip: 'Search',
              onPressed: () => debugPrint('Search button is pressed.'),
            ),
          ],
        ),
        body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.only(top: 30),
                    child: Image.asset(
                      "recource/images/login_icon_logo.png",
                      fit: BoxFit.fill,
                    ),
                  )
                ],
              ),
              phoneInputSection(),
              codeInputSection(),
              Container(
                padding: EdgeInsets.only(top: 8, right: 16),
                child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                  TextButton(
                      onPressed: loginCon.phone.toString().length == 0
                          ? null
                          : () {
                              loginCon.sendCode(2);
                            },
                      child: Text(
                          "Obtener la verificación por mensaje de voz >",
                          style: TextStyle(
                              color: Color(0xFF8399EE), fontSize: 12)))
                ]),
              ),
              Obx((() => Container(
                  height: 80,
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.only(top: 30, left: 16, right: 16),
                  child: ElevatedButton(
                      style: ButtonStyle(
                          backgroundColor: MaterialStatePropertyAll<Color>(
                              loginCon.isValidPhoneAndCode == RxBool(true)
                                  ? Color(0xFF3154E2)
                                  : Color(0xFFC1CBF6))),
                      child: Text("Iniciar sesión/Registrarse",
                          style: TextStyle(
                              color: Color(0xFFFFFFFF), fontSize: 14)),
                      onPressed: loginCon.isValidPhoneAndCode == RxBool(true)
                          ? () {
                              loginCon.loginRequest();
                            }
                          : null)))),
              Spacer(),
              privacyText()
            ],
          ),
        ));
  }

  Widget phoneInputSection() {
    return inputBackWidget(
      "recource/images/login_icon_phone.png",
      "Número celular",
      Row(
        children: [
          Text(
            "+${loginCon.phonePrefix}",
            style: TextStyle(color: Color(0xFF666666), fontSize: 14),
          ),
          Expanded(
              child: Container(
            padding: const EdgeInsets.only(left: 8),
            child: TextField(
                // autofocus: true,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(loginCon.phoneInputLength)
                ],
                style: const TextStyle(color: Color(0xFF333333), fontSize: 14),
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: "Introduzca su número de teléfono",
                    hintStyle: TextStyle(color: Color(0xFF999999))),
                // obscureText: true,
                onChanged: (value) {
                  Get.find<LoginController>().checkPhoneString(value);
                }),
          ))
        ],
      ),
    );
  }

  Widget codeInputSection() {
    return inputBackWidget(
      "recource/images/login_icon_otp.png",
      "Código de verificación",
      Row(
        children: [
          Expanded(
            child: TextField(
                // autofocus: true,
                style: TextStyle(color: Color(0xFF333333), fontSize: 14),
                keyboardType: TextInputType.number,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(loginCon.codeInputLength)
                ],
                decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: "Introduzca su número de teléfono",
                    hintStyle: TextStyle(color: Color(0xFF999999))),
                onChanged: (value) {
                  Get.find<LoginController>().checkCodeString(value);
                }),
          ),
          Obx(() => ElevatedButton(
              style: ButtonStyle(
                  backgroundColor: MaterialStatePropertyAll<Color>(
                      loginCon.phone.toString().isEmpty
                          ? Color(0xFFC1CBF6)
                          : Color(0xFF3154E2))),
              onPressed: loginCon.phone.toString().isEmpty
                  ? null
                  : () {
                      loginCon.startCountDown();
                    },
              child: Text(
                  [0, 60].contains(loginCon.countDown.toInt())
                      ? "Conseguir"
                      : "${loginCon.countDown.toInt()}s",
                  style:
                      const TextStyle(color: Color(0xFFFFFFFF), fontSize: 14))))
        ],
      ),
    );
  }

  Widget inputBackWidget(String iconName, String title, Widget content) {
    return Container(
      padding: const EdgeInsets.only(left: 30, right: 30, top: 30),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(
                width: 18,
                height: 18,
                child: Image.asset(iconName),
              ),
              Container(
                width: 8,
              ),
              Text(
                title,
                style: const TextStyle(color: Color(0xFF333333), fontSize: 12),
              )
            ],
          ),
          Container(
              margin: const EdgeInsets.only(top: 8),
              padding: const EdgeInsets.only(left: 8, right: 8),
              height: 50,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  border: Border.all(width: 1, color: const Color(0xFFCCCCCC))),
              child: content)
        ],
      ),
    );
  }

  Widget privacyText() {
    return Container(
      padding: const EdgeInsets.only(bottom: 30, left: 16, right: 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          RichText(
              text: TextSpan(
                  text: "注册即代表同意",
                  style:
                      const TextStyle(color: Color(0xFF666666), fontSize: 12),
                  children: [
                TextSpan(
                  text: "《隐私协议》",
                  style: TextStyle(color: Color(0xFF3154E2), fontSize: 12),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.to(PravicyPage());
                    },
                )
              ]))
        ],
      ),
    );
  }
}
